import axios, { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessage } from "element-plus";
import { getToken, removeToken } from "./auth";
import router from "@/router";

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: "/api", // 使用相对路径，依赖代理配置
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加token
    const token = getToken();
    if (token && config.headers) {
      config.headers["Authorization"] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    console.error("Request error:", error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data;

    // 如果是文件下载，直接返回
    if (response.config.responseType === "blob") {
      return response;
    }

    // 统一处理响应
    if (res.code === 200) {
      return res.data;
    } else {
      // 显示错误消息
      ElMessage.error(res.message || "请求失败");
      return Promise.reject(new Error(res.message || "请求失败"));
    }
  },
  error => {
    let message = "网络错误";

    if (error.response) {
      const errorData = error.response.data;
      // 优先使用后端返回的错误信息
      if (errorData && errorData.message) {
        message = errorData.message;
      } else {
        switch (error.response.status) {
          case 400:
            message = errorData?.message || "请求参数错误";
            break;
          case 401:
            message = "未授权，请重新登录";
            removeToken();
            router.push("/login");
            break;
          case 403:
            message = "拒绝访问";
            break;
          case 404:
            message = "请求地址不存在";
            break;
          case 500:
            message = "服务器内部错误";
            break;
          default:
            message = `连接错误${error.response.status}`;
        }
      }
    } else if (error.code === "ECONNABORTED") {
      message = "请求超时";
    } else if (error.message.includes("Network Error")) {
      message = "网络连接异常";
    }

    console.error("API Error:", error);
    ElMessage.error(message);
    return Promise.reject(error);
  }
);

export default service;
